using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net;
using System.Xml;
using ViewOnAddInsAPI.Helper.Security;
using ViewOnAddInsAPI.Device;
using ViewOnAddInsAPI.HostContract;

#region Copyright (c) 2006, 2007, 2008 ViewOn Media Services. All rights reserved.

/*
 Copyright (c) 2006, 2007, 2008 ViewOn Media Services. All rights reserved.
 This work is copyrighted in its entirety. Permission to use "ViewOn.tv"
 material may be granted only after we receive a written request from you,
 and you receive written permission from us.

 While ViewOn Media Services provides the information herein to anyone,
 we retain copyright on all code, text, graphic images, and other content.
 This means that you may not distribute the code, the text or graphics to others without the
 express written permission of ViewOn Media Services; "mirror" this information on your server
 without our permission; or modify or reuse the code, text or graphics on our servers.
 You may print copies of the information for your own personal use; and, you may reference
 the Service from your own documents. Any commercial use of this material is prohibited without
 the written permission of ViewOn Media Services. In all copies of this information, you must
 retain this notice and any other copyright notices originally included with such information.

 This material may be protected by U.S. and International Copyright laws, and you are legally
 bound by the copyright notices on those systems.

 "ViewOn" logos and other official symbols or graphics may not be used in connection with any
 product or service that has not been expressly authorized in advance in writing or in any manner
 that is likely to cause confusion among the users of this or other Web sites or among the public.
 All other seals, graphics or trademarks of organizations not affiliated with ViewOn Media Services
 that appear on this site are the property of their respective owners.

 ViewOn Media Services reserve all other rights. 
*/

#endregion

#region ViewOn.tv Source Code Licence

/*
This license governs use of the ViewOn.tv software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Summary

The source code is made available to view for reference purposes or to contribute to the project only. Developers may not distribute or modify the code for commercial or non-commercial purposes without express Agreement of View On Media Services.

2. Definitions

The terms "reproduce," "reproduction," and "distribution" have the same meaning here as under U.S. copyright law.
"Licensor" means the company "ViewOn Media Services".
"You" means the licensee of the software, who is not engaged in designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software.
"Your company" means the company you worked for when you downloaded the software.
"Reference use" means use of the software within your company as a reference, in read only form, for the sole purposes of debugging and maintaining your products. For clarity, "reference use" does NOT include (a) the right to use the software for purposes of designing, developing, or testing other software, that has the same or substantially the same features or functionality as the software, and (b) the right to distribute the software outside of your company.
"Licensed patents" means any Licensor patent claims which read directly on the software as distributed by the Licensor under this license.

3. Grant of Rights

(A) Copyright Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free copyright license to reproduce the software for reference use.
(B) Patent Grant- Subject to the terms of this license, the Licensor grants you a non-transferable, non-exclusive, worldwide, royalty-free patent license under licensed patents for reference use.
4. Limitations
(A) No Trademark License- This license does not grant you any rights to use the Licensor's name, logo, or trademarks.
(B) If you begin patent litigation against the Licensor over patents that you think may apply to the software (including a cross-claim or counterclaim in a lawsuit), your license to the software ends automatically.
(C) The software is licensed "as-is." You bear the risk of using it. The Licensor gives no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the Licensor excludes the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */

#endregion

namespace ViewOnAddInsAPI.Media
{
    /// <summary>
    /// This class manage a "Genre" list of online radios.
    /// </summary>
    sealed public class ViewOnRadioGenre : RadioGenre
    {

        #region Variables

        private XmlEncrypter _xmlEncrypter = Host.CreateEncrypter();
        private XmlCustomContext _context;

        #endregion

        #region Variables

        // The associated database file
        public string DBFile;

        #endregion

        #region Constructor

        public ViewOnRadioGenre(string dbFile, string title)
            : base(title)
        {
            DBFile = dbFile;
        }

        #endregion

        #region LoadRadios

        public override void LoadRadios()
        {
            if (_isLoaded)
                return;
            _isLoaded = true;

            Radios.Clear();

#if !IS_ADMINISTRATIVE_MODE

            //---- Auto update
            AutoUpdate();

#else
            //---- Load
            XmlDocument XmlDatabase = LoadXmlDatabase(Host.CachePath);

            //---- Create the empty Db
            if (XmlDatabase == null)
            {
                XmlDatabase = new XmlDocument();
                XmlDatabase.LoadXml("<db></db>");
                _xmlEncrypter.SaveEncryptedXML(XmlDatabase, Host.CachePath + DBFile);
                return;
            }

            //---- Add a Context for extended XPath functions
            _context = new XmlCustomContext((NameTable)XmlDatabase.NameTable);
            _context.AddNamespace("ext", "http://www.ViewOn.tv/");

            //---- Scan file
            XmlNodeList nodes = XmlDatabase.SelectNodes("/db/Radio");
            foreach (XmlNode node in nodes)
                Radios.Add(LoadXmlRadio(node));
#endif
        }

        #endregion

        #region Auto-update

        //<summary>
        //Load the remote database and update the local radios DB.
        //</summary>
        //<returns></returns>
        private bool AutoUpdate()
        {
            string remoteDbURL = "http://www.viewon.tv/_RemoteCache/" + DBFile;
            string localDbURL = Host.CachePath + "autoupdate\\" + DBFile;

            //---- Download the file
            if (!DownloadDatabaseFile(remoteDbURL, localDbURL))
                return false;

            //---- Clean the db
            for (int index = Radios.Count - 1; index > -1; index--)
                if (Radios[index].Source == RadioSource.ViewOn)
                    Radios.RemoveAt(index);

            //---- Add the new entries
            XmlDocument updateDb = LoadXmlDatabase(Host.CachePath + "autoupdate\\");

            XmlNodeList nodes = updateDb.SelectNodes("/db/Radio");
            foreach (XmlNode node in nodes)
                Radios.Add(LoadXmlRadio(node));

            //---- Save the new file
            SaveChanges();

            //---- Delete the file
            File.Delete(localDbURL);

            return true;
        }

        private bool DownloadDatabaseFile(string remoteDbURL, string localDbURL)
        {
            try
            {
                IWebProxy proxy = WebProxy.GetDefaultProxy();
                GlobalProxySelection.Select = proxy;
                GlobalProxySelection.Select.Credentials = CredentialCache.DefaultCredentials;

                WebRequest request = WebRequest.Create(remoteDbURL);
                request.Proxy = proxy;

                //---- Retreive the stream
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                System.IO.Stream stream = response.GetResponseStream();

                //---- Create the file
                Directory.CreateDirectory(Host.CachePath + "autoupdate\\");
                FileStream fileStream = new FileStream(localDbURL, FileMode.OpenOrCreate, FileAccess.Write);

                //---- Download
                byte[] buffer = new byte[256];
                int len = stream.Read(buffer, 0, 256);
                while (len > 0)
                {
                    fileStream.Write(buffer, 0, len);

                    // Next chunk
                    len = stream.Read(buffer, 0, 256);
                }

                response.Close();
                stream.Close();
                fileStream.Close();
            }
            catch (Exception e)
            {
                return false;
            }

            return true;
        }

        #endregion

        #region SaveChanges

        public void SaveChanges()
        {
            string xml = "<db>" + Environment.NewLine; ;

            foreach (Radio radio in Radios)
            {
                xml += "<Radio";

                xml += " Title=\"" + XmlConvert.EncodeLocalName(radio.Title) + "\"";
				xml += " Id=\"" + XmlConvert.EncodeLocalName(radio.RadioId) + "\"";
                

                if (radio.Source == RadioSource.ViewOn)
                    xml += " Source=\"VO\"";
                else
                    xml += " Source=\"USER\"";

                xml += " BitRate=\"" + radio.BitRate + "\"";
                xml += " Genre=\"" + XmlConvert.EncodeLocalName(radio.Genre) + "\"";
                xml += " Rating=\"4\"";
                xml += " Description=\"" + XmlConvert.EncodeLocalName(radio.Description) + "\"";
                xml += " PictureUrl=\"\"";
                xml += " SiteUrl=\"" + XmlConvert.EncodeLocalName(radio.SiteUrl) + "\"";
                xml += " StreamUrl=\"" + XmlConvert.EncodeLocalName(radio.StreamUrl) + "\"";
                xml += " Country=\"" + XmlConvert.EncodeLocalName(radio.Country) + "\"";
                xml += " Language=\"" + XmlConvert.EncodeLocalName(radio.Language) + "\"";
                xml += " Priority=\"" + radio.Priority + "\"";

                xml += "/>" + Environment.NewLine;
            }

            xml += "</db>";

            ////---- Save
            XmlDocument XmlDatabase = new XmlDocument();
            XmlDatabase.LoadXml(xml);
            ////XmlDatabase.Save(Host.CachePath + DBFile);
            _xmlEncrypter.SaveEncryptedXML(XmlDatabase, Host.CachePath + DBFile);
        }

        #endregion

        #region Helpers

        private XmlDocument LoadXmlDatabase(string directory)
        {
            return _xmlEncrypter.LoadEncryptedXML(directory + DBFile);

            //XmlDocument XmlDatabase = new XmlDocument();
            //try
            //{
            //    XmlDatabase.Load(path);
            //}
            //catch
            //{
            //    XmlDatabase = null;
            //}

            //return XmlDatabase;
        }

        private Radio LoadXmlRadio(XmlNode node)
        {
            Radio radio = new Radio();
            try
            {
                radio.RadioId = XmlConvert.DecodeName(node.Attributes["Id"].Value);
            }
            catch { radio.RadioId = ""; }
            radio.Title = XmlConvert.DecodeName(node.Attributes["Title"].Value);
            string source = XmlConvert.DecodeName(node.Attributes["Source"].Value);
            if (source == "USER")
                radio.Source = RadioSource.User;
            else
                radio.Source = RadioSource.ViewOn;
            radio.Genre = XmlConvert.DecodeName(node.Attributes["Genre"].Value);
            radio.Rating = Int32.Parse(node.Attributes["Rating"].Value);
            radio.Description = XmlConvert.DecodeName(node.Attributes["Description"].Value);
            radio.BitRate = XmlConvert.DecodeName(node.Attributes["BitRate"].Value);
            radio.PictureUrl = XmlConvert.DecodeName(node.Attributes["PictureUrl"].Value);
            radio.SiteUrl = XmlConvert.DecodeName(node.Attributes["SiteUrl"].Value);
            radio.StreamUrl = XmlConvert.DecodeName(node.Attributes["StreamUrl"].Value);
            radio.Country = XmlConvert.DecodeName(node.Attributes["Country"].Value);
            radio.Language = XmlConvert.DecodeName(node.Attributes["Language"].Value);
            radio.Priority = Int32.Parse(node.Attributes["Priority"].Value);

            return radio;
        }

        #endregion

    }
}
